package com.zklh.leetcode.top100;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 字符串解码算法实现
 *
 * @version 1.0
 * @Author tongnan
 * @Date 2023/9/20
 */
public class Solution394 {
    public String decodeString(String s) {
        Deque<String> deque = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        int current = 0;
        while (current < s.length()) {
            if (isNumber(s.charAt(current))) {
                int numberStart = current;
                while (isNumber(s.charAt(current))) current++;
                deque.push(s.substring(numberStart, current));
                current -= 1;
            } else if (isLeftBracket(s.charAt(current)) || isLetter(s.charAt(current))) {
                deque.push(s.substring(current, current+1));
            } else if (isRightBracket(s.charAt(current))) {
                sb.delete(0, sb.length());
                while (!isLeftBracket(deque.peek().charAt(0))) {
                    sb.insert(0,deque.poll());
                }
                deque.poll();
                int twice =  Integer.parseInt(deque.poll());
                String repeatStr = sb.toString();
                for (int i = 0; i < twice-1; i++) {
                    sb.append(repeatStr);
                }
                deque.push(sb.toString());
            }
            current++;
        }
        sb.delete(0, sb.length());

        deque.forEach(s1 -> sb.insert(0,s1));
        return sb.toString();
    }
    public boolean isNumber(char c) {
        return c <= '9' && c >= '0';
    }
    public boolean isLetter(char c) {
        return  c <= 'z' && c >= 'a';
    }
    public boolean isLeftBracket(char c) {
        return c == '[';
    }
    public boolean isRightBracket(char c) {
        return c == ']';
    }

    public static void main(String[] args) {
        Solution394 solution394 = new Solution394();
        System.out.println(solution394.decodeString("3[a]2[bc]"));
        System.out.println(solution394.decodeString("3[a2[c]]"));
    }
}